package com.yipingnai.blog.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yipingnai.blog.model.RespBean;
import com.yipingnai.blog.model.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: jiangym
 * @Date: 2020/5/18 16:55
 */
public class URLFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        if(req.getServletPath().startsWith("/admin")){
            if("POST".equals(req.getMethod()) && "/admin/login".equals(req.getServletPath())){

                String code = req.getParameter("code");
                String verify_code = (String) req.getSession().getAttribute("verify_code");
                if (code == null || verify_code == null || "".equals(code) || !verify_code.toLowerCase().equals(code.toLowerCase())) {
                    //验证码不正确
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(RespBean.error("验证码错误")));
                    out.flush();
                    out.close();
                    return;
                } else {
                    filterChain.doFilter(req, resp);
                }
            }else{
                User user = (User)req.getSession().getAttribute("user");
                if(user == null){
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(RespBean.error("请先登录")));
                    out.flush();
                    out.close();
                    return;
                }else {
                    filterChain.doFilter(req, resp);
                }
            }

        }else {
            filterChain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
